﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SugarFineUI.CodeGenerator.code;
using SugarFineUI.CodeTemplates;
using FineUIPro;
using SqlSugar;
using SugarFineUI.Framework.Uitility;
using Template_ModelFirst = SugarFineUI.CodeTemplates.FineUIPro.Template_ModelFirst;
using Template_ModelFirstBase = SugarFineUI.CodeTemplates.FineUIPro.Template_ModelFirst.FineuiBase;

namespace SugarFineUI.CodeGenerator.ModelFirst
{
    public partial class ModelToFineuiProCode : CodeBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ttbDB.Text = Server.MapPath("~/bin/SugarFineUI.Enties.dll");
                txb_DbXml.Text = Server.MapPath("~/bin/SugarFineUI.Enties.xml");
            }
        }

        protected void Btn_SetSimpleCode_OnClick(object sender, EventArgs e)
        {
            //https://www.cnblogs.com/junjieok/p/4949806.html  获取特性和值
            Assembly assembly = Assembly.LoadFile(ttbDB.Text);
            //Type[] types = assembly.GetTypes();
            if (hd_tables.Text.Length == 0)
            {
                NotifyError("请选择类名称！");
                return;
            }

            bool haveXML = false;//是否有注释文件
            DataSet ds = new DataSet(); ;
            if (File.Exists(txb_DbXml.Text))
            {
                ds.ReadXml(txb_DbXml.Text);
                haveXML = true;
            }


            string[] tables = hd_tables.Text.Split(',');
            var list = assembly.GetExportedTypes().Where(p => tables.Contains(p.Name)).OrderBy(p => p.Name).ToList();//public类型 Model名称

            Type pType;
            DbColumnInfo clm;
            List<DbColumnInfo> columnList;
            PropertyInfo[] propertyInfos;
            SugarColumn sugarColumn;
            object attribute;
            DataRow[] dataRows;
            int startIndex = 0;
            try
            {
                for (int i = 0; i < list.Count; i++)
                {
                    columnList = new List<DbColumnInfo>();
                    pType = list[i];
                    propertyInfos = pType.GetProperties(BindingFlags.Instance | BindingFlags.Public);//获取字段属性

                    foreach (PropertyInfo pi in propertyInfos)
                    {
                        clm = new DbColumnInfo();
                        clm.TableName = pType.Name;
                        clm.DbColumnName = pi.Name;
                        clm.DataType = Template_ModelFirstBase.GetDataTypeName(pi.PropertyType.FullName);//获取类型
                        if (haveXML)//获取备注信息
                        {
                            var datatable = ds.Tables["member"];

                            dataRows = datatable.Select(string.Format("name = 'P:{0}.{1}'", pType.FullName, pi.Name));
                            if (dataRows != null && dataRows.Length > 0)
                            {
                                clm.ColumnDescription = StringHelper.GetBetweenStr(dataRows[0]["summary"].ToString(), "Desc:", "Default:").Trim();
                                clm.DefaultValue = StringHelper.GetBetweenStr(dataRows[0]["summary"].ToString(), "Default:", "Nullable:").Trim();

                                startIndex = dataRows[0]["summary"].ToString().IndexOf("Nullable:");
                                if (startIndex < 0)
                                {
                                    clm.IsNullable = true;//可以为null
                                }
                                else//获取Nullable: 后面的值。如果是true ，代表可以为null。
                                {
                                    clm.IsNullable = !"false".Equals(dataRows[0]["summary"].ToString().Substring(startIndex + "Nullable:".Length), StringComparison.InvariantCultureIgnoreCase);
                                }
                            }
                        }
                        else
                        {
                            clm.ColumnDescription = string.Empty;
                            clm.DefaultValue = string.Empty;
                            clm.IsNullable = true;//可以为null
                        }

                        attribute = pi.GetCustomAttributes(typeof(SugarColumn), false).FirstOrDefault();
                        if (attribute is SugarColumn)//获取特性和值
                        {
                            sugarColumn = attribute as SugarColumn;
                            clm.IsPrimarykey = sugarColumn.IsPrimaryKey;
                            clm.IsIdentity = sugarColumn.IsIdentity;
                        }
                        else
                        {
                            clm.IsPrimarykey = false;
                            clm.IsIdentity = false;
                        }
                        columnList.Add(clm);
                    }

                    SetCodeByTableName(pType.Name, columnList);
                }
            }
            catch (Exception exception)
            {
                NotifyError(exception.Message);
                return;
            }

            NotifyInformation("生成简单代码成功!");
        }

        /// <summary>
        /// 生成页面代码，根据表名称
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="cm">字段信息集合</param>
        /// <returns></returns>
        private void SetCodeByTableName(string tableName, List<DbColumnInfo> cm)
        {
            try
            {
                string namespace2Str = txb_Path.Text.Trim().Replace("/", ".");

                string savePath = txb_savePath.Text.Trim() + "\\" + txb_Path.Text + "\\" + tableName + "\\";

                TableModel table = new TableModel();
                table.Columns = cm;
                table.ClassnameStr = txb_BaseClassName.Text;
                table.NamespaceStr = txb_NameSpace.Text;
                table.Namespace2Str = namespace2Str;
                table.ModelName = txb_ModelName.Text;
                table.TableName = tableName;

                CreateFineuiProCode_ModelFirst(savePath, table, cb_isHaveViewPage.Checked);
            }
            catch (Exception ex)
            {
                throw new Exception("生成代码有问题：表名称(" + tableName + ")" + ex.Message);
            }
        }

        protected void btn_ShowCode_OnClick(object sender, EventArgs e)
        {
            Assembly assembly = Assembly.LoadFile(ttbDB.Text);
            //Type[] types = assembly.GetTypes();
            if (hd_tables.Text.Length == 0)
            {
                NotifyError("请选择类名称！");
                return;
            }

            bool haveXML = false;//是否有注释文件
            DataSet ds = new DataSet(); ;
            if (File.Exists(txb_DbXml.Text))
            {
                ds.ReadXml(txb_DbXml.Text);
                haveXML = true;
            }

            string[] tables = hd_tables.Text.Split(',');
            var list = assembly.GetExportedTypes().Where(p => p.Name == tables[0]).OrderBy(p => p.Name).ToList();//public类型 Model名称

            Type pType;
            DbColumnInfo clm;
            List<DbColumnInfo> columnList;
            PropertyInfo[] propertyInfos;
            SugarColumn sugarColumn;
            object attribute;
            DataRow[] dataRows;
            int startIndex = 0;
            try
            {

                columnList = new List<DbColumnInfo>();
                pType = list[0];
                propertyInfos = pType.GetProperties(BindingFlags.Instance | BindingFlags.Public);//获取字段属性

                foreach (PropertyInfo pi in propertyInfos)
                {
                    clm = new DbColumnInfo();
                    clm.TableName = pType.Name;
                    clm.DbColumnName = pi.Name;
                    clm.DataType = Template_ModelFirstBase.GetDataTypeName(pi.PropertyType.FullName);//获取类型
                    if (haveXML)//获取备注信息
                    {
                        var datatable = ds.Tables["member"];

                        dataRows = datatable.Select(string.Format("name = 'P:{0}.{1}'", pType.FullName, pi.Name));
                        if (dataRows != null && dataRows.Length > 0)
                        {
                            clm.ColumnDescription = StringHelper.GetBetweenStr(dataRows[0]["summary"].ToString(), "Desc:", "Default:").Trim();
                            clm.DefaultValue = StringHelper.GetBetweenStr(dataRows[0]["summary"].ToString(), "Default:", "Nullable:").Trim();

                            startIndex = dataRows[0]["summary"].ToString().IndexOf("Nullable:");
                            if (startIndex < 0)
                            {
                                clm.IsNullable = true;//可以为null
                            }
                            else//获取Nullable: 后面的值。如果是true ，代表可以为null。
                            {
                                clm.IsNullable = !"false".Equals(dataRows[0]["summary"].ToString().Substring(startIndex + "Nullable:".Length), StringComparison.InvariantCultureIgnoreCase);
                            }
                        }
                    }
                    else
                    {
                        clm.ColumnDescription = string.Empty;
                        clm.DefaultValue = string.Empty;
                        clm.IsNullable = true;//可以为null
                    }

                    attribute = pi.GetCustomAttributes(typeof(SugarColumn), false).FirstOrDefault();
                    if (attribute is SugarColumn)//获取特性和值
                    {
                        sugarColumn = attribute as SugarColumn;
                        clm.IsPrimarykey = sugarColumn.IsPrimaryKey;
                        clm.IsIdentity = sugarColumn.IsIdentity;
                    }
                    else
                    {
                        clm.IsPrimarykey = false;
                        clm.IsIdentity = false;
                    }
                    columnList.Add(clm);
                }

                string namespace2Str = txb_Path.Text.Trim().Replace("/", ".");

                //string savePath = txb_savePath.Text.Trim() + "\\" + txb_Path.Text + "\\" + pType.Name + "\\";

                // 单页显示
                List<DbColumnInfo> cm = columnList;//字段信息集合  TableModel table=new TableModel();
                TableModel table = new TableModel();
                table.Columns = cm;
                table.ClassnameStr = txb_BaseClassName.Text;
                table.NamespaceStr = txb_NameSpace.Text;
                table.Namespace2Str = namespace2Str;
                table.ModelName = txb_ModelName.Text;
                table.TableName = pType.Name;

                //add
                string templateInfo = Template_ModelFirst.FineuiAdd_cs.GetCode(table);
                lb_addCS.Text = ShowHighlightCode(templateInfo);

                templateInfo = Template_ModelFirst.FineuiAdd.GetCode(table);
                lb_addAspx.Text = ShowHighlightCode(templateInfo);

                //List
                templateInfo = Template_ModelFirst.FineuiList_cs.GetCode(table);
                lb_listCS.Text = ShowHighlightCode(templateInfo);

                templateInfo = Template_ModelFirst.FineuiList.GetCode(table);
                lb_listAspx.Text = ShowHighlightCode(templateInfo);

                //View
                templateInfo = Template_ModelFirst.FineuiView_cs.GetCode(table);
                lb_viewCS.Text = ShowHighlightCode(templateInfo);

                templateInfo = Template_ModelFirst.FineuiView.GetCode(table);
                lb_viewAspx.Text = ShowHighlightCode(templateInfo);

                PageContext.RegisterStartupScript("ShowHighlight();");

            }
            catch (Exception exception)
            {
                NotifyError(exception.Message);
                return;
            }
        }

        private static bool GetIsPrimaryKey(PropertyInfo pi)
        {
            var attribute = pi.GetCustomAttributes(typeof(SugarColumn), false).FirstOrDefault();
            if (attribute == null)
            {
                return false;
            }

            return ((SugarColumn)attribute).IsPrimaryKey;
        }

        private void BindTable()
        {
            //反射获取model名称
            //https://www.cnblogs.com/DHclly/p/9223326.html //反射获取注释
            //https://www.cnblogs.com/imyao/p/5263401.html
            Assembly assembly = Assembly.LoadFile(ttbDB.Text);
            //Type[] types = assembly.GetTypes();
            //assembly.GetExportedTypes();//public类型

            List<Type> list;

            if (ttbSearchTableName.Text.Length > 0)
            {
                list = assembly.GetExportedTypes().Where(p => p.Name.Contains(ttbSearchTableName.Text)).OrderBy(p => p.Name).ToList();
            }
            else
            {
                list = assembly.GetExportedTypes().OrderBy(p => p.Name).ToList();
            }

            cbl_tables.Items.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                cbl_tables.Items.Add(new CheckItem(list[i].Name, list[i].Name));
            }
        }

        protected void btn_DBlink_OnClick(object sender, EventArgs e)
        {
            BindTable();
        }

        protected void ttbSearchTableName_OnTrigger1Click(object sender, EventArgs e)
        {
            BindTable();
        }

        protected void ttbSearchTableName_OnTrigger2Click(object sender, EventArgs e)
        {
            BindTable();
        }
    }
}

/*
public static Dictionary<string, string> GetProperties<T>(T t)
{
    Dictionary<string, string> ret = new Dictionary<string, string>();

    if (t == null)
    {
        return null;
    }
    System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

    if (properties.Length <= 0)
    {
        return null;
    }
    foreach (System.Reflection.PropertyInfo item in properties)
    {
        string name = item.Name;                                                  //实体类字段名称
        string value = "" ;//ObjToStr(item.GetValue(t, null));                //该字段的值

        if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
        {
            ret.Add(name, value);        //在此可转换value的类型
        }
    }
    return ret;
}
*/
